﻿var app = angular.module('todoApp', [
    'ui.bootstrap',
    'ngSanitize',
    'ngRoute'
]);

app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
    $routeProvider
    .when('/', {
        templateUrl: '/app/views/TodosView.html',
        controller: 'TodoController',
        title: 'List of Todo Items'
    })
    .when('/completed', {
        templateUrl: '/app/views/CompletedView.html',
        controller: 'CompletedController',
        title: 'List of Completed Todo Items'
    })
    .when('/todo/:id', {
        templateUrl: '/app/views/TodoView.html',
        controller: 'ViewTodoController',
        title: 'Todo Item'
    })
    .when('/login', {
        templateUrl: '/app/views/LoginView.html',
        controller: 'LoginController',
        title: 'Login'
    })
    .otherwise({
        redirectTo: '/'
    });

    $httpProvider.interceptors.push('AuthService');
}]);

app.run(['$rootScope', '$route', function ($rootScope, $route) {
    $rootScope.$on('$routeChangeSuccess', function () {
        document.title = $route.current.title;
    });
}]);

//ng-write-whatever
app.directive('ngWriteWhatever', function () {
    return function (scope, element, attrs) {
        var templateElement = $(element);
        var value = templateElement.attr('ng-write-whatever');
        $(element).html('<em>' + value + '</em>');
    };
});

app.filter('search', function () {
    return function (items, searchTerm) {        
        if (!searchTerm)
            return items;

        searchTerm = searchTerm.toLowerCase();

        var filteredItems = [];

        angular.forEach(items, function (item) {
            for (var p in item) {
                if (item.hasOwnProperty(p) && p != 'id' && p != '$$hashKey') {
                    if (item[p] && typeof (item[p]) === 'string' && item[p].toLowerCase().indexOf(searchTerm) !== -1) {
                        if (filteredItems.indexOf(item) === -1) {
                            filteredItems.push(item);
                        }
                    }
                }                
            }

            //if (item.text.indexOf(searchTerm) !== -1) {
            //    filteredItems.push(item);
            //}
        })

        return filteredItems;
    };
});